package cn.ycq.im;

import cn.ycq.im.chat.netty.NettyChatServer;
import cn.ycq.im.commons.utils.FreemarkerRenderUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.mail.javamail.JavaMailSender;

import javax.annotation.PostConstruct;
import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.HashMap;
import java.util.Random;

@SpringBootApplication(exclude = FreeMarkerAutoConfiguration.class)
@MapperScan("cn.ycq.im.mapper")
public class ImApplicationStarterMain {

    @Autowired
    private JavaMailSender javaMailSender;
    @Autowired
    private MailProperties mailProperties;

    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(ImApplicationStarterMain.class, args);
        NettyChatServer chatServer = applicationContext.getBean(NettyChatServer.class);
        try {
            chatServer.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

 //  @PostConstruct
    public void sendMail(){

        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        try {
            mimeMessage.setFrom(new InternetAddress(mailProperties.getUsername(),"小于",mailProperties.getDefaultEncoding().toString()));
            mimeMessage.setRecipient(Message.RecipientType.TO,new InternetAddress("chaoqunyu9311@163.com"));
            mimeMessage.setSubject("测试邮件");

            HashMap<String, Object> props = new HashMap<>();
            props.put("vcode",String.valueOf(new Random().nextInt()));
            String render = FreemarkerRenderUtils.render("email-template.html", props);

            MimeBodyPart mimeBodyPart = new MimeBodyPart();
            mimeBodyPart.setContent(render,"text/html;charset=utf-8");

            MimeMultipart mimeMultipart = new MimeMultipart();
            mimeMultipart.addBodyPart(mimeBodyPart);

            mimeMessage.setContent(mimeMultipart);


            javaMailSender.send(mimeMessage);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
